package com.cultusoft.groovin.plugins.fitnesse;

import com.cultusoft.groovin.utils.SystemProperties;
import com.cultusoft.groovin.log.GroovinLogger
import com.cultusoft.groovin.configuration.Configuration

class FitnesseStatusVerifier {

    def logger = new GroovinLogger(this)
	
 	public void run() {
		waitForValidFitnesseServerStatus()
 	}
	
	protected String getErrorMessage() {
		return ""
	}
	
	protected boolean isFitnesseStatusValid(def isFitnesseAlive) {
		return false;
	}
	
 	private void waitForValidFitnesseServerStatus() {
        def configuration = new Configuration()
        def fitnesseProperties = configuration.getFitnesseProperties()
		def hostname = fitnesseProperties.getHostname()
		def port = fitnesseProperties.getPort()
	    InetAddress addr = InetAddress.getByName(hostname);
        SocketAddress socketAddress = new InetSocketAddress(addr, port);
		
        def isFitnesseStatusValid = false;
		for (i in 1..10) {
			def isFitnesseAlive = openSocketClient(socketAddress, 2000)
			if (isFitnesseStatusValid(isFitnesseAlive)) {
				isFitnesseStatusValid = true
				break;
			} else {
				logger.log(getErrorMessage())
				logger.log("Trying again in 2 seconds (" + (11-i) + " attempts left)")
				logger.log( "------------------------------------------------------------------------")
				Thread.sleep(2000)
			}
		}
		
		if (!isFitnesseStatusValid) {
			throw new RuntimeException (errorMessage)
		}
				
		
 	}
 	
 	def openSocketClient(def socketAddress, def timeoutMs) {
	    try {
	        Socket sock = new Socket();
	        sock.connect(socketAddress, timeoutMs);
	        sock.close()
	        return true;
	    } catch (Exception e) {}
	    
	    return false
 	}

}
